package com.groupbuying.currency.producer.service.impl;

import com.groupbuying.currency.producer.connector.CustomerFeign;
import com.groupbuying.currency.producer.connector.SysconfigFeign;
import com.groupbuying.currency.producer.constants.CommonConstants;
import com.groupbuying.currency.producer.constants.CurrencyConstants;
import com.groupbuying.currency.producer.context.FilterContextHandler;
import com.groupbuying.currency.producer.dao.CurrencyCustomerDao;
import com.groupbuying.currency.producer.dao.CurrencyCustomerLogDao;
import com.groupbuying.currency.producer.domain.CurrencyActivityDO;
import com.groupbuying.currency.producer.domain.CurrencyCustomerDO;
import com.groupbuying.currency.producer.domain.CurrencyCustomerLogDO;
import com.groupbuying.currency.producer.domain.CurrencyPlatformLogDO;
import com.groupbuying.currency.producer.service.CurrencyActivityService;
import com.groupbuying.currency.producer.service.CurrencyCustomerService;
import com.groupbuying.currency.producer.service.CurrencyPlatformLogService;
import com.groupbuying.currency.producer.utils.DateUtils;
import com.groupbuying.currency.producer.utils.MD5Utils;
import com.groupbuying.currency.producer.utils.apiresult.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class CurrencyCustomerServiceImpl implements CurrencyCustomerService {
    /**
     * 注册送积分的数量
     */
    @Value("${registCurrency:0}")
    private String REGIST_CURRENCY;

    @Autowired
    private CurrencyCustomerDao currencyCustomerDao;

    @Autowired
    private CurrencyCustomerLogDao currencyCustomerLogDao;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private CurrencyActivityService currencyActivityService;

    @Autowired
    private CustomerFeign customerFeign;

    @Autowired
    private CurrencyPlatformLogService currencyPlatformLogService;

    @Override
    public CurrencyCustomerDO get(String customerId) {
        return currencyCustomerDao.get(customerId);
    }

    @Override
    public List<CurrencyCustomerDO> list(Map<String, Object> map) {
        return currencyCustomerDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return currencyCustomerDao.count(map);
    }

    @Override
    public int save(CurrencyCustomerDO currencyCustomer) {
        return currencyCustomerDao.save(currencyCustomer);
    }

    @Override
    public int update(CurrencyCustomerDO currencyCustomer) {
        return currencyCustomerDao.update(currencyCustomer);
    }

    @Override
    public int remove(String customerId) {
        return currencyCustomerDao.remove(customerId);
    }

    @Override
    public int batchRemove(String[] customerIds) {
        return currencyCustomerDao.batchRemove(customerIds);
    }

    /**
     * Description 创建积分账户 <br>
     *
     * @return customerID
     * @author Ywxd <br>
     * @createDate 2019/4/15 17:41<br>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CurrencyCustomerDO createCurrencyCustomer(String customerID) {

        //先查询有无积分账户
        CurrencyCustomerDO currencyCustomerDO_already = currencyCustomerDao.get(customerID);
        if (currencyCustomerDO_already != null) {
            return currencyCustomerDO_already;
        }

        /* 创建积分账户逻辑 */
        /* 1、新建积分账户空对象等待填入 */
        CurrencyCustomerDO currencyCustomerDO = new CurrencyCustomerDO();

        /* 2、装配积分账户数据并存入库表 */
        currencyCustomerDO.setCustomerId(customerID);
        String format = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        currencyCustomerDO.setCreateTime(format);
        currencyCustomerDO.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);

        //查询积分活动
        CurrencyActivityDO currencyActivityDO = currencyActivityService.get(CurrencyConstants.ACTIVITY_REGIST);
        if (currencyActivityDO.getDelFlag().equals(CommonConstants.COMMON_FLAG_UNDEL) && currencyActivityDO.getEnableState().equals(CommonConstants.COMMON_STATE_UES)) {
            //活动进行中
            currencyCustomerDO.setUseCurrency(new BigDecimal(REGIST_CURRENCY));
            currencyCustomerDO.setFreezeCurrency(new BigDecimal(0));
            currencyCustomerDO.setTotalCurrency(new BigDecimal(REGIST_CURRENCY));
            int returnValue = currencyCustomerDao.save(currencyCustomerDO);
            /* 3、积分中心日志记录，需要和积分账户创建成为事务 */
            if (returnValue > 0) {
                /* 日志数据装配并储入库表 */
                CurrencyCustomerLogDO currencyCustomerLogDO = new CurrencyCustomerLogDO();
                //注册送积分活动
                currencyCustomerLogDO.setActivityId(CurrencyConstants.ACTIVITY_REGIST);
                currencyCustomerLogDO.setLogId(sysconfigFeign.createLogID());
                currencyCustomerLogDO.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);
                String create = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
                currencyCustomerLogDO.setCreateTime(create);
                currencyCustomerLogDO.setCustomerId(customerID);
                /* 2019/6/19 修复Bug：首次注册时payId设置为9个0 */
                currencyCustomerLogDO.setPayId("000000000");
                /* 碎银流向：01、活动；02、消费 */
                currencyCustomerLogDO.setCurrencySource(CurrencyConstants.CURRENCY_SOURCE_ACTIVITY);
                /* 碎银变化类型：01：增加：02减少，03：无变化 */
                currencyCustomerLogDO.setCurrencyType(CurrencyConstants.CURRENCY_TYPE_INCREASE);
                currencyCustomerLogDO.setCurrencyCount(new BigDecimal(REGIST_CURRENCY));
                //当前积分账户余额
                currencyCustomerLogDO.setCurrencyBalance(new BigDecimal(REGIST_CURRENCY));
                currencyCustomerLogDao.save(currencyCustomerLogDO);
                //活动减除
                currencyActivityDO.setSurplusCurrency(currencyActivityDO.getSurplusCurrency().subtract(new BigDecimal(REGIST_CURRENCY)));
                currencyActivityService.update(currencyActivityDO);

                //平台增加积分日志
                CurrencyPlatformLogDO currencyPlatformLogDO = new CurrencyPlatformLogDO();
                currencyPlatformLogDO.setActivityId(CurrencyConstants.ACTIVITY_REGIST);
                currencyPlatformLogDO.setLogId(sysconfigFeign.createLogID());
                currencyPlatformLogDO.setDelFlag(CommonConstants.COMMON_FLAG_UNDEL);
                currencyPlatformLogDO.setCreateTime(create);
                //发送给谁的customerId
                currencyPlatformLogDO.setCustomerId(customerID);
                currencyPlatformLogDO.setPayId(currencyCustomerLogDO.getLogId());
                currencyPlatformLogDO.setCurrencySource(CurrencyConstants.CURRENCY_SOURCE_ACTIVITY);
                currencyPlatformLogDO.setCurrencyType(CurrencyConstants.CURRENCY_TYPE_DECREASE);
                currencyPlatformLogDO.setCurrencyCount(new BigDecimal(REGIST_CURRENCY));
                currencyPlatformLogDO.setCurrencyBalance(currencyActivityDO.getSurplusCurrency());
                currencyPlatformLogService.save(currencyPlatformLogDO);

                //注册完送积分发送短信
                String msg = "恭喜您新用户注册成功，赠送" + REGIST_CURRENCY + "积分。";
                customerFeign.sendSmsWithCustomerId(customerID, msg);
            }
        } else {
            //活动结束
            currencyCustomerDO.setUseCurrency(new BigDecimal(0));
            currencyCustomerDO.setFreezeCurrency(new BigDecimal(0));
            currencyCustomerDO.setTotalCurrency(new BigDecimal(0));
            currencyCustomerDao.save(currencyCustomerDO);
        }
        return currencyCustomerDO;
    }

    @Override
    public ApiResult changeCurrencyPwd(Map<String, Object> mapParams) {
        Object tempParam = mapParams.get("password");
        String password = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("mobile");
        String mobile = tempParam == null ? null : tempParam.toString();

        //判断请求参数不为空
        if (StringUtils.isEmpty(password)) {
            return ApiResult.paramIsNull();
        }

        System.out.println(mobile);
        if (mobile.length() > 6 && !mobile.equals(FilterContextHandler.getUsername())) {
            //修改手机号与用户登录手机号不一致
            return ApiResult.failure();
        }

        String customerUuid = FilterContextHandler.getUserID();
        CurrencyCustomerDO currencyCustomerDO = new CurrencyCustomerDO();
        currencyCustomerDO.setCustomerId(customerUuid);
        currencyCustomerDO.setPassword(MD5Utils.encrypt(customerUuid, password));
        this.update(currencyCustomerDO);

        return ApiResult.operateSuccess();
    }

    @Override
    public Boolean checkCurrencyPwd(String customerId, String password) {
        CurrencyCustomerDO currencyCustomerDO = currencyCustomerDao.get(customerId);
        String password_new = MD5Utils.encrypt(customerId, password);
        if (currencyCustomerDO.getPassword().equals(password_new)) {
            return true;
        } else {
            return false;
        }
    }

}
